﻿using System;
using System.Collections.Generic;
using System.Linq;

using Ext.Net;
using BG.Data;
using BG.Service;
using Kwan.Data;
using System.Diagnostics;
using Kwan.Core;

namespace BG.Web.Admin.RoomStatus
{
    public partial class Default : UIPage
    {
        #region
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!X.IsAjaxRequest)
            {
                btnFreeOrder.Hidden = permit[4];
            }
        }

        protected void RefreshRoomDS(object sender, StoreRefreshDataEventArgs e)
        {
            string[] status = new string[] { "空洁房", "空脏房", "维修房", "住客房", "保留房" };
            var roomList = new Expression().List<VRoom>(VRoom.roomNO.Asc);
            //var roomClass = roomList.Distinct(p => p.ClassName, StringComparer.CurrentCultureIgnoreCase).ToList<VRoom>();
            var roomClass = roomList.Distinct(p => p.Floor, StringComparer.CurrentCultureIgnoreCase).ToList<VRoom>();
            var queryRoom = from VRoom t in roomClass
                            select new
                            {
                                Title = t.Floor,
                                Items = (from VRoom tt in roomList.Where(c => c.Floor == t.Floor)
                                         select new
                                         {
                                             Title = tt.RoomNO,
                                             //Icon = "resources/images/shop-open.png",
                                             Id = "Room_" + tt.EntityID,
                                             Price = tt.Price == 0 ? tt.ClassPrice : tt.Price,
                                             Type = tt.ClassName,
                                             Status = status[tt.Status],
                                             CustomerName = tt.CustomerName,
                                             IsComputer = tt.IsComputer,
                                             IsMaQue = tt.IsMaQue
                                         })
                            };
            //var queryRoom = from VRoom tt in roomList
            //                select new
            //                {
            //                    Title = tt.RoomNO,
            //                    //Icon = "resources/images/shop-open.png",
            //                    Id = "Room_" + tt.EntityID,
            //                    Price = tt.Price == 0 ? tt.ClassPrice : tt.Price,
            //                    Type = tt.ClassName,
            //                    Status = status[tt.Status],
            //                    CustomerName = tt.CustomerName
            //                };
            roomStore.DataSource = queryRoom;
            roomStore.DataBind();
            //winRooms.Show();
        }

        [DirectMethod]
        public void BindCustomerName(string NameCN)
        {
            CustomerDS.AddRecord(NameCN);
            CustomerDS.DataBind();
            txtCustomerName.SetValue(NameCN);
        }

        [DirectMethod(ShowMask = true, Msg = "加载中...", Timeout = 10000)]
        public void SetCustomer(string NameCN)
        {
            TCustomer customer = (TCustomer.nameCN == NameCN).ListFirst<TCustomer>();
            SetCustomerForm(customer);
            customer = null;
        }

        private void SetCustomerForm(TCustomer customer)
        {
            if (customer == null) return;
            txtCustomerName.Text = customer.NameCN;
            txtAddress.Text = customer.Address;
            txtCountry.Text = customer.Country;
            txtIDNO.Text = customer.IDNO;
            txtIDType.SetValue(customer.IDType);
            txtLevel.SetValue(customer.Level);
            txtPhone.Text = customer.Phone;
            txtSex.SetValue(customer.Sex);
            txtCustomerMemo.Text = customer.Memo;
        }

        [DirectMethod(ShowMask = true, Msg = "加载中...", Timeout = 10000)]
        public void ChangeProStatus()
        {
            (TProductOrder.orderID == txtOrderID.Text & TProductOrder.status == 1).Edit<TProductOrder>(a => a.Status = 0);
        }
        #endregion

        protected void SubmitRoomDS2(object sender, StoreSubmitDataEventArgs e)
        {
            int orderID = int.Parse(txtOrderID.Text);
            AddOrder(orderID, e.Json);
        }

        private void AddOrder(int orderID, string json, params object[] args)
        {
            IList<VRoom> roomList = JSON.Deserialize<IList<VRoom>>(json);
            IList<TOrder> orderlist = (TOrder.pid == orderID & TOrder.status == 1).List<TOrder>();  //子订单
            using (IConnectinContext cc = DBContext.Context1)
            {
                cc.BeginTransaction();
                IList<TOrder> saveList = new List<TOrder>();
                foreach (VRoom room in roomList)
                {
                    if (room.EntityID == 0) continue;
                    TOrder order = new TOrder();
                    if (orderlist.Count > 0)
                    {
                        IList<TOrder> matchOrder = orderlist.Where(a => a.RoomID == room.EntityID).ToList();
                        if (matchOrder.Count > 0)
                        {
                            order = matchOrder[0];
                        }
                    }
                    else if (args[0] != null)
                    {
                        order.EntityID = 0;
                        order.CreatedDate = DateTime.Now;
                        TOrder pOrder = args[0] as TOrder;
                        order.Pid = orderID;
                        order.Deposit = 0;
                        order.CheckInPrice = room.ClassPrice;
                        order.CheckInRoomPrice = room.Price == 0 ? room.ClassPrice : room.Price;
                        order.CardNO = pOrder.CardNO; order.CheckInDate = pOrder.CheckInDate; order.CheckInType = pOrder.CheckInType; order.CustomerID = pOrder.CustomerID; order.Days = pOrder.Days; order.Memo = pOrder.Memo; order.RoomID = room.EntityID; order.Status = pOrder.Status; order.UserID = pOrder.UserID;
                    }

                    
                    DBContext.Save(order);
                    (TRoom.entityID == room.EntityID).Edit<TRoom>(a => a.Status = 3);
                }
                //删除 设置status=3
                IList<TOrder> matchPro = orderlist.Where(a => !roomList.Any(b => b.EntityID == a.Pid)).ToList();
                foreach (TOrder order in matchPro)
                {
                    (TProductOrder.productID == order.Pid & TProductOrder.orderID == orderID)
                        .Edit<TProductOrder>(a => a.Status = 3);    //作废订单
                }
                cc.Commit();
            }
            ConsumeDS.CommitChanges();
        }

        private void BindRoomDS(int orderID)
        {
            using (IConnectinContext cc = DBContext.Context1)
            {
                cc.BeginTransaction();
                IList<VRoom> roomList = new Expression().List<VRoom>();
                TOrder order = (TOrder.entityID == orderID & TOrder.status == 1).ListFirst<TOrder>();
                int roomID = int.Parse(txtRoomID.Text);
                if (order == null)
                {
                    roomList = roomList.Where(a => a.Status == 0 && a.EntityID != roomID).ToList();
                    RoomDS1.DataSource = roomList;
                    RoomDS1.DataBind();
                    RoomDS2.DataSource = new List<VRoom>();
                    RoomDS2.DataBind();
                }
                else
                {
                    IList<TOrder> orderList = (TOrder.pid == orderID & TOrder.status == 1).List<TOrder>();   //合并结账
                    orderList.Add(order);

                    cc.Commit();

                    List<VRoom> room2 = roomList.Where(a => orderList.Any(b => b.RoomID == a.EntityID)).ToList();
                    if (room2.Count > 0)
                    {
                        room2 = room2.FindAll(delegate(VRoom t)
                        {
                            t.ClassPrice = Convert.ToInt32(orderList.Last(a => a.RoomID == t.EntityID).CheckInPrice);
                            return true;
                        });
                        RoomDS2.DataSource = room2;
                        RoomDS2.DataBind();
                    }
                    IList<VRoom> room1 = roomList.Except<VRoom>(room2).ToList();
                    RoomDS1.DataSource = room1;
                    RoomDS1.DataBind();
                    room1 = null;
                    room2 = null;
                }

                DisposeDS();
            }
            //winProduct.Show();
        }

        private void DisposeDS()
        {
            RoomDS1.Dispose();
            RoomDS2.Dispose();
            ProductDS1.Dispose();
            ConsumeDS.Dispose();
        }

        [DirectMethod(ShowMask = true)]
        public void SubmitConsume(int roomID,string json)
        {
            IList<TProduct> proList = JSON.Deserialize<IList<TProduct>>(json);

        }

        protected void SubmitConsumeDS(object sender, StoreSubmitDataEventArgs e)
        {
            int orderID = int.Parse(txtOrderID.Text);
            AddConsume(orderID, e.Json);
        }

        private void AddConsume(int orderID,string json)
        {
            IList<TConsume> newCSList = JSON.Deserialize<IList<TConsume>>(json);
            IList<TConsume> consumelist = (TConsume.orderID == orderID).List<TConsume>();
            using (IConnectinContext cc = DBContext.Context1)
            {
                cc.BeginTransaction();
                foreach (TConsume cs in newCSList)
                {
                    if (cs.EntityID == 0) continue;
                    TConsume consume = new TConsume();
                    if (consumelist.Count > 0)
                    {
                        IList<TConsume> match = consumelist.Where(a => a.Type == 2 && a.Item == cs.Item).ToList();
                        if (match.Count > 0)
                        {
                            consume = match[0];
                        }
                    }
                    TUser u = ConfigManager.Instance.IndentityUser();
                    consume.CreatedDate = DateTime.Now;
                    consume.Item = cs.Item;
                    consume.OrderID = orderID;
                    consume.ProductID = cs.ProductID;
                    consume.Price = cs.Price;
                    consume.Nett = cs.Price * cs.Total;     //实际价格
                    consume.Type = 2;
                    consume.Total = cs.Total;
                    consume.UserID = u.EntityID;
                    consume.Status = 1;
                    DBContext.Save(consume);
                }


                //删除 设置status=3
                IList<TConsume> matchPro = consumelist.Where(a => a.Type == 2 && !newCSList.Any(b => b.Item == a.Item)).ToList();
                foreach (TConsume order in matchPro)
                {
                    (TConsume.orderID == order.EntityID)
                        .Edit<TConsume>(a => a.Status = 3); //冲红
                }
                cc.Commit();
            }
            ConsumeDS.CommitChanges();
        }

        private void BindConsumeDS(int orderID)
        {
            using (IConnectinContext cc = DBContext.Context1)
            {
                cc.BeginTransaction();
                IList<TProduct> proList = new Expression().List<TProduct>(TProduct.cid.Asc);
                IList<TConsume> consumeList = (TConsume.orderID == orderID & TConsume.status == 1).List<TConsume>(TConsume.type.Asc);
                cc.Commit();
                IList<TProduct> leftPro = proList.Where(a => !consumeList.Any(b => b.Item == a.NameCN && b.Type == 2)).ToList();
                ProductDS1.DataSource = leftPro;
                ProductDS1.DataBind();

                ConsumeDS.DataSource = consumeList;
                ConsumeDS.DataBind();
            }
        }

        protected void RefreshCustomerDS(object sender, StoreRefreshDataEventArgs e)
        {
            IList<TCustomer> list = new Expression().List<TCustomer>();
            string query = e.Parameters["query"];
            if (!string.IsNullOrEmpty(query) && query != "*")
            {
                list = list.Where(plant => plant.NameCN.ToLower().Contains(query.ToLower())).ToList();
            }

            CustomerDS.DataSource = list;
            CustomerDS.DataBind();
            list = null;
            CustomerDS.Dispose();
            //winRooms.Show();
        }

        [DirectMethod(ShowMask = true)]
        public void ChangeStatus(int roomID, int status)
        {
            (TRoom.entityID == roomID & TRoom.status != 3).Edit<TRoom>(a => a.Status = status);
            roomStore.DataBind();
        }

        [DirectMethod(ShowMask = true)]
        public void SaveChangeRoom(int oldRoomID)
        {
            using (IConnectinContext cc = DBContext.Context1)
            {
                cc.BeginTransaction();
                int newRoomID = Convert.ToInt32(txtChangeRoom.Value);
                TUser u = ConfigManager.Instance.IndentityUser();
                TOrder order = (TOrder.roomID == oldRoomID & TOrder.status == 1).ListFirst<TOrder>();
                if (order != null)
                {
                    TOrder newOrder = new TOrder() { CardNO = order.CardNO, CheckInDate = order.CheckInDate, CheckInPrice = order.CheckInPrice, CheckInRoomPrice = order.CheckInRoomPrice, CheckInType = order.CheckInType, CreatedDate = DateTime.Now, CustomerID = order.CustomerID, Days = order.Days, Deposit = order.Deposit, DisCount = order.DisCount, FinalRoomPrice = order.FinalRoomPrice, Memo = order.Memo, Pid = order.Pid, RoomID = newRoomID, Status = 1, UserID = u.EntityID };
                    order.Status = 5;
                    (TRoom.entityID == oldRoomID & TRoom.status == 3).Edit<TRoom>(a => a.Status = 1);
                    (TRoom.entityID == newRoomID & TRoom.status == 0).Edit<TRoom>(a => a.Status = 3);
                    DBContext.Save(order);
                    DBContext.Save(newOrder);

                    IList<TConsume> csList = (TConsume.orderID == order.EntityID).List<TConsume>();
                    foreach(TConsume cs in csList){
                        TConsume newCS = new TConsume()
                        {
                            CreatedDate = DateTime.Now,
                            Item = cs.Item,
                            Nett = cs.Nett,
                            OrderID = newOrder.EntityID,
                            Price = cs.Price,
                            ProductID = cs.ProductID,
                            RoomID = newRoomID,
                            Total = cs.Total,
                            Status = 1,
                            Type = cs.Type,
                            UserID = u.EntityID
                        };
                        DBContext.Save(newCS);
                    }
                    (TConsume.orderID == order.EntityID).Edit<TConsume>(a => a.Status = 5);
                    TRoomChange rc = new TRoomChange() { CreatedDate = DateTime.Now, NewRoomID = newRoomID, OldRoomID = oldRoomID, UserID = u.EntityID };
                    //TLog log = new TLog();
                    //log.Action = 2; log.CreatedDate = DateTime.Now; log.ModuleID = 4;
                    //log.Memo = string.Format("房间{0}=>{1}", oldRoomID, newRoomID);
                    //log.UserID = u.EntityID;
                    DBContext.Save(rc);

                }
                cc.Commit();
            }
            winChangeRoom.Hide();
            roomStore.DataBind();
        }

        protected void GetExamplesNodes(object sender, NodeLoadEventArgs e)
        {
            if (e.NodeID == "root")
            {
                IList<VRoom> roomList = (TRoom.status == 0).List<VRoom>();
                if (roomList.Count > 0)
                {
                    TreeNodeCollection nodes = new TreeNodeCollection(false);
                    IList<VRoom> ClassList = roomList.Distinct(a=>a.Cid).ToList(); //父节点
                    foreach (VRoom c in ClassList)
                    {
                        TreeNode node = new TreeNode();
                        node.Icon = Icon.Report;
                        node.NodeID = c.EntityID.ToString();
                        node.Text = c.ClassName;

                        IList<VRoom> childList = roomList.Where(a => a.Cid == c.Cid).ToList();
                        foreach (VRoom r in childList)
                        {
                            TreeNode child = new TreeNode();
                            child.NodeID = r.EntityID.ToString();
                            child.Text = r.RoomNO;
                            child.Leaf = true;
                            node.Nodes.Add(child);
                        }
                        nodes.Add(node);
                    }
                    e.Nodes = nodes;
                }

            }
        }

        [DirectMethod(ShowMask = true)]
        public void RoomClick(int roomID)
        {
            VRoom room = (TRoom.entityID == roomID).ListFirst<VRoom>();
            if (room.Status == 3)
            {
                RoomCheckOut(room.EntityID); return;
            }
            rdoCheckInType3.Checked = true;
            HideInput(true);
            txtOrderID.Text = "";
            if (room.Status != 0) return;
            TConfig config = ConfigManager.Instance.LoadFromCache();

            Stopwatch sw = new Stopwatch(); sw.Start();
            //房卡信息
            if (config.AutoReadCard)
            {
                TCard t = new TCard() { BuildNo = "1", CardNo = "1", EndDate = "201109091124", FloorNo = "1", Memo = "", Port = 1, RoomNo = "" };
                int readInfo;
                Card.ReadCard(t, out readInfo);
                if (readInfo < 0)
                    ExtHelper.GetNotification("系统提示", Card.ErrMessage(readInfo) + "<br>" + sw.ElapsedMilliseconds).Show();
                txtCardNo.Text = t.CardNo;
            }
            else { bgCardNO.Hidden = true; }

            //房间没有限制押金，从默认配置取
            if (room.Deposit == 0)
            {
                room.Deposit = config.Deposit;
            }

            txtDays.Text = "1";
            txtDeposit.Text = room.Deposit.ToString();


            //房价处理
            TUser u = ConfigManager.Instance.IndentityUser();
            int days = Convert.ToInt32(txtDays.Text);
            double roomPrice = room.Price > 0 ? room.Price : room.ClassPrice;
            double roomReserve = room.Reserve > 0 ? room.Reserve : room.ClassReserve;

            //打折
            //double maxDiscount = (double)u.Discount;
            //txtDisCount.MinValue = maxDiscount;
            //txtDisCount.IndicatorText = maxDiscount + "-100 (85=8.5折)";
            //double finalPrice = (int)maxDiscount * roomPrice; //最终打折价格


            double finalPrice = roomPrice;
            if (finalPrice < roomReserve)
            {
                finalPrice = roomReserve;
            }

            txtRoomID.Text = room.EntityID.ToString();
            txtRoomNO.Text = room.RoomNO;
            txtRoomClass.Text = room.ClassName;
            
            txtRoomPrice.Text = roomPrice.ToString();

            SetCustomerForm(new TCustomer() { IDType = 1, Level = 0, Sex = 1, Country = "中国" });

            BindConsumeDS(0);
            BindRoomDS(0);


            winCheckIN.Show();
            TaskManager1.StopTask(0);
            
        }

        [DirectMethod(ShowMask = true, Msg = "加载中...", Timeout = 10000)]
        public void RoomCheckOut(int roomID)
        {
            HideInput(false);
            VRoom room = (VRoom.entityID == roomID).ListFirst<VRoom>();
            TUser u = ConfigManager.Instance.IndentityUser();
            if (room == null || room.Status != 3)
            {
                return;
            }

            VOrder order = (VOrder.roomNO == room.RoomNO & VOrder.status == 1).ListFirst<VOrder>(VOrder.checkInDate.Desc);
            //if (order.Pid > 0)
            //{
            //    order = (VOrder.entityID == order.Pid & VOrder.status == 1).ListFirst<VOrder>();
            //}
            txtOrderID.Text = order.EntityID.ToString();
            //设置客人信息
            TCustomer customer = (TCustomer.entityID == order.CustomerID).ListFirst<TCustomer>();
            SetCustomerForm(customer);

            double roomPrice = order.CheckInRoomPrice;
            double roomHalfPrice = room.HalfPrice > 0 ? room.HalfPrice : room.ClassHalfPrice;
            double roomNightPrice = room.NightPrice > 0 ? room.NightPrice : room.ClassNightPrice;
            double roomHourPrice = room.HourPrice > 0 ? room.HourPrice : room.ClassHourPrice;

            if (order.CheckInRoomPrice != order.CheckInPrice && order.CheckInType != 1)    //入住价格不等于房价
            {
                roomPrice = order.CheckInPrice;
                roomHalfPrice = 0; roomNightPrice = 0;
            }

            if (order.CheckInType == 1)     //钟点房计算
            {
                roomHourPrice = order.CheckInPrice;
                btnFinalPrice.Text =
                    PriceManager.Instance.GetHourPrice(order.CheckInDate, DateTime.Now, roomPrice, roomHalfPrice, roomHourPrice).ToString();
            }
            else
            {
                btnFinalPrice.Text =
                    PriceManager.Instance.GetFinalPrice(order.CheckInDate, DateTime.Now, roomPrice, roomHalfPrice, roomNightPrice).ToString();

            }
            btnCheckInDate.Text = order.CheckInDate.ToString();
            bgCardNO.Hidden = false;

            //double maxDiscount = (double)u.Discount;
            //txtDisCount.MinValue = maxDiscount;
            //txtDisCount.IndicatorText = maxDiscount + "-100 (85=8.5折)";

            if (order == null)
            {
                ExtHelper.GetNotification("系统提示", "无此房间信息！请检查卡片或房间信息是否被删除！").Show();
                return;
            }

            txtRoomNO.Text = order.RoomNO;
            txtRoomClass.Text = order.RoomClassName;
            txtCardNo.Text = order.CardNO;
            txtRoomPrice.Text = order.CheckInPrice.ToString();
            txtRoomID.Text = room.EntityID.ToString();
            txtDays.Text = order.Days.ToString();
            txtDeposit.Text = order.Deposit.ToString();

            BindConsumeDS(order.EntityID);
            BindRoomDS(order.EntityID);


            winCheckIN.Show();
        }

        [DirectMethod(ShowMask = true)]
        public void SaveCheckIN(string customerName, string csJson,string roomJson)
        {
            using (IConnectinContext cc = DBContext.Context1)
            {
                cc.BeginTransaction();
                TConfig config = ConfigManager.Instance.LoadFromCache();
                VRoom room = (TRoom.entityID == int.Parse(txtRoomID.Text)).ListFirst<VRoom>();
                //房卡信息
                TCard card = new TCard(){ BuildNo = "0", CardNo = "0", EndDate = "198611241124", FloorNo = "0", Memo = "", Port = 1, RoomNo = "" };
                if (config.AutoReadCard)
                {
                    int readInfo;
                    Card.ReadCard(card, out readInfo);
                    if (readInfo != 0)
                    {
                        ExtHelper.GetNotification("系统提示", "读卡失败！错误信息：" + Card.ErrMessage(readInfo)).Show();
                        return;
                    }
                    //写卡
                    card.RoomNo = room.RoomNO;
                    int writeInfo = Card.WriteCard(card);
                    if (writeInfo != 0)
                    {
                        ExtHelper.GetNotification("系统提示", "写卡失败！错误信息：" + Card.ErrMessage(writeInfo)).Show();
                        return;
                    }
                }
                //房价处理
                TUser u = ConfigManager.Instance.IndentityUser();
                //入住天数
                int days = Convert.ToInt32(txtDays.Text);
                //入住类型
                int checkInType = 3;
                double roomPrice;

                rgCheckInType.CheckedItems.ForEach(delegate(Radio radio)
                {
                    checkInType = int.Parse(radio.ID.Replace("rdoCheckInType", ""));
                });
                //[免收,钟点房,半天房,全天房]
                switch (checkInType)
                {
                    default:
                    case 3:
                        roomPrice = room.Price > 0 ? room.Price : room.ClassPrice; break;
                    case 1:
                        days = 1;
                        roomPrice = room.HourPrice > 0 ? room.HourPrice : room.ClassHourPrice; break;
                    case 2:
                        days = 1;
                        roomPrice = room.HalfPrice > 0 ? room.HalfPrice : room.ClassHalfPrice; break;
                    case 0:
                        roomPrice = 0; break;
                }

                double maxDiscount = (double)u.Discount;
                int roomDiscount = int.Parse(txtDisCount.Text);
                if (roomDiscount < u.Discount)
                {
                    roomDiscount = u.Discount;
                }

                double finalPrice = roomPrice * (float)(roomDiscount / 100) * days; //最终房价

                //自动限价
                if (config.AutoReserve)
                {
                    double roomReserve = room.Reserve > 0 ? room.Reserve : room.ClassReserve;
                    if (finalPrice < roomReserve)
                    {
                        finalPrice = roomReserve;
                    }
                }

                TOrder order = new TOrder();
                order.RoomID = Convert.ToInt32(txtRoomID.Text);
                order.Status = 1;
                order.CheckInDate = DateTime.Now;
                order.Days = Convert.ToInt32(txtDays.Text);
                order.Deposit = Convert.ToInt32(txtDeposit.Text);
                order.DisCount = roomDiscount;
                order.CheckInType = checkInType;
                order.CardNO = card.CardNo;
                order.CreatedDate = DateTime.Now;
                order.CheckInPrice = double.Parse(txtRoomPrice.Text);
                order.CheckInRoomPrice = room.Price == 0 ? room.ClassPrice : room.Price;
                order.UserID = u.EntityID;

                customerName = string.IsNullOrEmpty(txtCustomerName.RawText) ? customerName : txtCustomerName.RawText;

                if (!string.IsNullOrEmpty(customerName))
                {
                    TCustomer customer = (TCustomer.nameCN == customerName).ListFirst<TCustomer>();
                    if (customer == null) customer = new TCustomer();
                    customer.Address = txtAddress.Text;
                    customer.Country = txtCountry.Text;
                    customer.IDNO = txtIDNO.Text;
                    customer.IDType = Convert.ToInt32(txtIDType.Value);
                    customer.Level = Convert.ToInt32(txtLevel.Value);
                    customer.Memo = txtCustomerMemo.Text;
                    customer.NameCN = customerName;
                    customer.Phone = txtPhone.Text;
                    customer.Sex = Convert.ToInt32(txtSex.Value);
                    DBContext.Save(customer);
                    order.CustomerID = customer.EntityID;
                }
                DBContext.Save(order);

                (TRoom.entityID == order.RoomID).Edit<TRoom>(a => a.Status = 3);    //住客房
                AddConsume(order.EntityID, csJson);
                AddOrder(order.EntityID, roomJson, order);

                //收押金
                txtDPOrderID.Text = order.EntityID.ToString();
                txtDPReceivable.Text = order.Deposit.ToString();
                txtDPMemo.Text = string.Empty;
                txtDPCashPay.Text = string.Empty;
                txtDPChange.Text = string.Empty;
                txtDPPosPay.Text = string.Empty;

                order = null;

                roomStore.DataBind();
                winCheckIN.Hide();
                cc.Commit();
                winCollectDP.Show();
            }
        }

        [DirectMethod(ShowMask = true)]
        public void FreeOrder(int finalRoomPrice, string json)
        {
            if (!permit[4])
            {
                return;
            }
            double proPrice = 0;
            IList<TProduct> proList = JSON.Deserialize<IList<TProduct>>(json);
            if (proList.Count > 0)
            {
                foreach(TProduct t in proList)
                {
                    proPrice += t.Count * t.Price;
                }
            }
            TOrder order = (TOrder.entityID == int.Parse(txtOrderID.Text)).ListFirst<TOrder>();
            if (proPrice > 0)
            {
                txtReceivable.Text = proPrice.ToString();
                txtPayDeposit.Text = order.Deposit.ToString();
                double payDisCount = (double)(((100m - Convert.ToDecimal(txtDisCount.Text)) / 100) * (decimal)proPrice);
                txtPayDisCount.Text = payDisCount.ToString();
                txtPaid.Text = (proPrice - payDisCount - order.Deposit).ToString();
                winCheckOut.Show();
            }
            else
            {
                order.Status = 5;   //免收
                //order.TotalPrice = finalRoomPrice + proPrice;
                using (IConnectinContext cc = DBContext.Context1)
                {
                    cc.BeginTransaction();
                    (TRoom.entityID == order.RoomID).Edit<TRoom>(a => a.Status = 1);    //空脏房
                    DBContext.Save(order);
                    cc.Commit();
                }
                winCheckIN.Hide();
                roomStore.DataBind();
            }
            
        }

        [DirectMethod(ShowMask = true)]
        public void ShowCheckOut(int finalRoomPrice, string csJson)
        {
            double proPrice = 0;
            List<TConsume> proList = JSON.Deserialize<List<TConsume>>(csJson);
            if (proList.Count > 0)
            {
                proList.FindAll(delegate(TConsume t)
                {
                    if (t.EntityID != 0)
                    {
                        proPrice += t.Total * t.Price;
                        return true;
                    }
                    return true;
                });
            }
            TCollection dpCL = (TCollection.orderID == int.Parse(txtOrderID.Text) & TCollection.type == 1).ListFirst<TCollection>();
            double deposit = dpCL == null ? 0 : dpCL.CashPay + dpCL.PosPay;
            double receivable = finalRoomPrice + proPrice;
            double payDisCount = (double)(((100m - Convert.ToDecimal(txtDisCount.Text)) / 100) * (decimal)receivable);
            txtReceivable.Text = receivable.ToString();
            txtPayDeposit.Text = deposit.ToString();
            txtPayDisCount.Text = payDisCount.ToString();
            double paid = receivable - payDisCount - deposit;
            
            if (paid < 0)
            {
                txtCashPay.Text = "0";
                txtPosPay.Text = "0";
                txtChange.Text = paid.ToString();
                txtPaid.Text = "0";
            }
            else
            {
                txtCashPay.Text = string.Empty;
                txtPosPay.Text = string.Empty;
                txtChange.Text = string.Empty;
                txtPaid.Text = paid.ToString();
            }

            winCheckOut.Show();
        }

        [DirectMethod(ShowMask = true)]
        public void SaveCheckOut(double totalRoomPrice,string csJson)
        {
            TOrder order = (TOrder.entityID == int.Parse(txtOrderID.Text)).ListFirst<TOrder>();
            TUser u = ConfigManager.Instance.IndentityUser();
            double paid = double.Parse(txtPaid.Text);
            double cashPay = double.Parse(txtCashPay.Text);
            double posPay = double.Parse(txtPosPay.Text);

            bool isLosses = (cashPay + posPay) < paid;
            //写入房费账单
            TCollection collect = new TCollection();
            collect.BillNO = DateTime.Now.ToString("yyyyMMddHHmmss");
            if (isLosses)
            {
                collect.Status = 4; //挂账
                order.Status = 4;
            }
            else
            {
                collect.Status = 2;
                order.Status = 2;
            }
            
            collect.Change = double.Parse(txtChange.Text);
            collect.CreatedDate = DateTime.Now;
            collect.OrderID = order.EntityID;
            collect.CashPay = cashPay;
            collect.PosPay = posPay;
            collect.Paid = paid;
            collect.Pid = 0;
            collect.RoomID = order.RoomID;
            collect.UserID = u.EntityID;
            collect.Memo = txtMemo.Text;
            collect.Receivable = double.Parse(txtReceivable.Text);
            collect.Received = order.Deposit;
            collect.Type = 0;
            DBContext.Save(collect);

            order.Memo = txtMemo.Text;
            using (IConnectinContext cc = DBContext.Context1)
            {
                cc.BeginTransaction();
                (TRoom.entityID == order.RoomID).Edit<TRoom>(a => a.Status = 1);    //空脏房
                //处理商品
                List<TConsume> csList = JSON.Deserialize<List<TConsume>>(csJson);
                csList.FindAll(delegate(TConsume t)
                {
                    if (t.Type == 2)
                    {
                        //写入消费品账单
                        TCollection proCollect = new TCollection();
                        proCollect.BillNO = collect.BillNO + t.ProductID;
                        proCollect.CreatedDate = DateTime.Now;
                        proCollect.OrderID = order.EntityID;
                        proCollect.UserID = u.EntityID;
                        proCollect.Receivable = t.Nett * t.Total;
                        proCollect.Pid = collect.EntityID;
                        proCollect.Type = 3;
                        DBContext.Save(proCollect);

                        (TConsume.orderID == order.EntityID).Edit<TConsume>(a => a.Status = 2);
                    }
                    return true;
                });

                TCollection roomCollect = new TCollection();
                roomCollect.BillNO = collect.BillNO + "0";   //房间费用
                roomCollect.CreatedDate = DateTime.Now;
                roomCollect.OrderID = order.EntityID;
                roomCollect.UserID = u.EntityID;
                roomCollect.Receivable = totalRoomPrice;
                roomCollect.Pid = collect.EntityID;
                roomCollect.Type = 2;
                DBContext.Save(roomCollect);

                DBContext.Save(order);
                cc.Commit();
            }
            roomStore.DataBind();
            winCheckOut.Hide();
            winCheckIN.Hide();
        }

        [DirectMethod(ShowMask = true)]
        public void SaveDeposit()
        {
            TUser u = ConfigManager.Instance.IndentityUser();
            TCollection cl = new TCollection();
            cl.BillNO = DateTime.Now.ToString("yyyyMMddHHmmss") + "01";
            cl.CashPay = double.Parse(txtDPCashPay.Text);
            cl.Change = double.Parse(txtDPChange.Text);
            cl.CreatedDate = DateTime.Now;
            cl.OrderID = int.Parse(txtDPOrderID.Text);
            cl.Memo = txtDPMemo.Text;
            cl.PosPay = double.Parse(txtDPPosPay.Text);
            cl.UserID = u.EntityID;
            cl.Status = 2;
            cl.Type = 1;
            DBContext.Save(cl);
            winCollectDP.Hide();
        }

        public void ConfirmCheckOut()
        {
            //收款后修改订单及房间状态
            TCard card = new TCard() { BuildNo = "0", CardNo = "0", EndDate = "198611241124", FloorNo = "0", Memo = "", Port = 1, RoomNo = "" };
            int writeInfo = Card.WriteCard(card);
            //if(writeInfo==0)
            using (IConnectinContext cc = DBContext.Context1)
            {
                cc.BeginTransaction();
                (VOrder.roomNO == card.RoomNo).Edit<TOrder>(a => a.Status = 3);
                (TRoom.entityID == Convert.ToInt32(txtRoomID.Text)).Edit<TRoom>(a => a.Status = 1);
                cc.Commit();
                roomStore.DataBind();
                winCheckIN.Hide();
            }
        }

        private void HideInput(bool isCheckIn)
        {
            btnSaveCheckIN.Hidden = !isCheckIn;
            btnCheckOut.Hidden = isCheckIn;
            bgFinalPrice.Hidden = isCheckIn;
            bgCheckInDate.Hidden = isCheckIn;
            bgCardNO.Hidden = isCheckIn;
            btnProduct.Hidden = isCheckIn;
            rgCheckInType.ReadOnly = !isCheckIn;

            winCheckIN.Title = isCheckIn ? "登记入住" : "退房结账";

            txtDeposit.ReadOnly = !isCheckIn;
            txtDays.ReadOnly = !isCheckIn;
            txtRoomPrice.ReadOnly = !isCheckIn;
        }

        [DirectMethod]
        public void ChangeRoomPrice(bool isCheckOut)
        {
            if (isCheckOut) return;
            VRoom room = (TRoom.entityID == int.Parse(txtRoomID.Text)).ListFirst<VRoom>();
            if (room != null)
            {
                int checkInType = 3;
                double roomPrice = 0;
                rgCheckInType.CheckedItems.ForEach(delegate(Radio radio)
                {
                    checkInType = int.Parse(radio.ID.Replace("rdoCheckInType", ""));
                });
                switch (checkInType)
                {
                    default:
                    case 3:
                        roomPrice = room.Price > 0 ? room.Price : room.ClassPrice; break;
                    case 1:
                        roomPrice = room.HourPrice > 0 ? room.HourPrice : room.ClassHourPrice; break;
                    case 2:
                        roomPrice = room.HalfPrice > 0 ? room.HalfPrice : room.ClassHalfPrice; break;
                }
                txtRoomPrice.Text = roomPrice.ToString();
            }
        }

        [DirectMethod]
        public void MatchInternetTime()
        {
            DateTime dt1 = DateTime.Now;
            DateTime dt2 = SystemTime.GetInternetTime();
            double outMin = (dt2 - dt1).TotalMinutes;
            if (outMin > 20)
            {
                TLog log = new TLog();
                log.Action = 1; log.CreatedDate = dt2;
                log.Memo = string.Format("当前登录用户：{0}。系统时间相差{1}分钟。", Page.User.Identity.Name, outMin);
                log.ModuleID = 11;
                DBContext.Save(log);
            }
        }
        [DirectMethod]
        public void AddPro(string json)
        {
            IList<TProduct> proList = JSON.Deserialize<IList<TProduct>>(json);
            IList<TConsume> csList = new List<TConsume>();
            if (!string.IsNullOrEmpty(txtOrderID.Text))
            {
                csList = (TConsume.orderID == int.Parse(txtOrderID.Text)).List<TConsume>();
            }
            int i=100;
            foreach (TProduct pro in proList)
            {
                TConsume t = new TConsume();
                t.EntityID = i; t.Item = pro.NameCN; t.Price = pro.Price; t.Total = 1; t.CreatedDate = DateTime.Now; t.ProductID = pro.EntityID;
                t.Nett = pro.Price;
                csList.Add(t);
                i--;
            }
            ConsumeDS.DataSource = csList;
            ConsumeDS.DataBind();
        }
        
    }
}